package com.pe.pgn.clubpgn.webapp.controller.tarjetaempresa;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import com.pe.pgn.clubpgn.common.CLPConstantes;
import com.pe.pgn.clubpgn.domain.ClpbTarjetaEmpresa;
import com.pe.pgn.clubpgn.domain.beans.BNTarjetaEmpresa;
import com.pe.pgn.clubpgn.service.SincronizacionFlotaService;
import com.pe.pgn.clubpgn.service.TarjetaEmpresaService;
import com.pe.pgn.clubpgn.webapp.controller.BaseFormController;
import com.pe.pgn.clubpgn.webapp.util.CalendarUtil;

@Controller
@RequestMapping("/tarjetaempresa/**")
public class TarjetaEmpresaController extends BaseFormController{

	@Autowired
	private TarjetaEmpresaService tarjetaEmpresaService;
	
	@Autowired
	private SincronizacionFlotaService sincronizacionService; 
	
	@RequestMapping(value = "/tarjetaempresalist.html")
    public @ModelAttribute("tarjetaEmpresa")BNTarjetaEmpresa buscarTarjetasEmpresa(
    			@ModelAttribute("tarjetaEmpresa") BNTarjetaEmpresa tarjetaEmpresa,
    			@RequestParam(value = "search", required = false) String search, Model model) {
		
		if(StringUtils.isBlank(search)){
			
			List<BNTarjetaEmpresa> tarjetasEmpresa = tarjetaEmpresaService.buscarTarjetasEmpresas(null, Boolean.TRUE);
			model.addAttribute("tarjetasEmpresa", tarjetasEmpresa);			
			return new BNTarjetaEmpresa();
		}
		
		List<BNTarjetaEmpresa> tarjetasEmpresa = tarjetaEmpresaService.buscarTarjetasEmpresas(tarjetaEmpresa, Boolean.FALSE);
		model.addAttribute("tarjetasEmpresa", tarjetasEmpresa);		
		return tarjetaEmpresa;
    }	
	
	@RequestMapping(value = "/tarjetaempresagroupform.html", method = RequestMethod.GET)
	public @ModelAttribute("tarjetaEmpresa") BNTarjetaEmpresa crearGrupoTarjetaEmpresa(Model model) {
		
		BNTarjetaEmpresa tarjetaEmpresa = tarjetaEmpresaService.obtenerMaximoCodigoTarjetaEmpresa();
		return tarjetaEmpresa;
	}
	
	@RequestMapping(value = "/tarjetaempresagroupform.html", method = RequestMethod.POST)
	public String guardarGrupoTarjetaEmpresa(@ModelAttribute("tarjetaEmpresa")  BNTarjetaEmpresa tarjetaEmpresa,
			BindingResult result, SessionStatus status, HttpServletRequest request, Model model) {

		try {
			
			if (result.hasErrors()) {
				model.addAttribute("tarjetaEmpresa", tarjetaEmpresa);
				return "/tarjetaempresa/tarjetaempresagroupform";
			}
			
			tarjetaEmpresa.setDaFechaInicioVigencia(CalendarUtil.stringToCalendar(CLPConstantes.DATE_PATTERN, tarjetaEmpresa.getDaVigenciaInicio()));
			tarjetaEmpresa.setDaFechaFinVigencia(CalendarUtil.stringToCalendar(CLPConstantes.DATE_PATTERN, tarjetaEmpresa.getDaVigenciaFin()));
			
			if(tarjetaEmpresa.getDaFechaInicioVigencia().compareTo(tarjetaEmpresa.getDaFechaFinVigencia()) > 0){
				
				saveError(request, getText("errors.comparando.fechas", 
						new Object []{getText("common.vigencia.fin", request.getLocale()),
						getText("common.vigencia.inicio", request.getLocale())}, 
						request.getLocale()));
				model.addAttribute("tarjetaPersona", tarjetaEmpresa);
				return "/tarjetaempresa/tarjetaempresagroupform";
			}
			
			boolean existeRango = tarjetaEmpresaService.existeRango(tarjetaEmpresa);
			if(existeRango){
				model.addAttribute("tarjetaEmpresa", tarjetaEmpresa);
				saveError(request, getText("tarjetaempresaform.error.exists.group", request.getLocale()));
				return "/tarjetaempresa/tarjetaempresagroupform";
			}
			
			tarjetaEmpresaService.guardarGrupoTarjetasEmpresas(tarjetaEmpresa);			
			saveMessage(request, getText("tarjetaempresaform.group.added", request.getLocale()));
			return "redirect:tarjetaempresalist.html";
			
		} catch (Exception e) {
			model.addAttribute("tarjetaEmpresa", tarjetaEmpresa);
			saveError(request, getText("errors.general", request.getLocale()));
			return "/tarjetaempresa/tarjetaempresagroupform";
		}
	}		

	@RequestMapping(value = "/tarjetaempresaform.html", method = RequestMethod.GET)
	public @ModelAttribute("tarjetaEmpresa")  ClpbTarjetaEmpresa verTarjeta(
				@RequestParam(value = "id", required = false) Long id, Model model) {
		
		if (id != null) {
			
			ClpbTarjetaEmpresa tarjetaEmpresa = tarjetaEmpresaService.obtenerTarjetaEmpresa(id);			
			Map<String, Object> flota = tarjetaEmpresaService.obtenerDatosClientePorFlota(tarjetaEmpresa.getCoFlotaVehiculo());
			
			model.addAttribute("flota", flota);			
			return tarjetaEmpresa;
		}
		
		return new ClpbTarjetaEmpresa();
	}
	
	@RequestMapping(value = "/tarjetaempresaform.html", method = RequestMethod.POST)
	public String actualizarTarjetaEmpresa(@ModelAttribute("tarjetaEmpresa") 
			ClpbTarjetaEmpresa tarjetaEmpresa, BindingResult result, SessionStatus status, 
			HttpServletRequest request) {
		
		try {
			
			if (result.hasErrors()) {
				return "/tarjetaempresa/tarjetaempresaform";
			}
			
        	if (tarjetaEmpresa.getId() != null){        		
        		ClpbTarjetaEmpresa tarjetaEmpresaInicial = tarjetaEmpresaService.
        		obtenerTarjetaEmpresa(tarjetaEmpresa.getId());
        		
        		sincronizacionService.guardarSyncPorTarjetaEmpresa(tarjetaEmpresa,tarjetaEmpresaInicial);
        	}
			
			tarjetaEmpresaService.actualizarTarjetaEmpresa(tarjetaEmpresa);
			saveMessage(request, getText("tarjetaempresaform.updated", tarjetaEmpresa.getCoCodigoTarjetaEmpresa(), 
					request.getLocale()));
			return "redirect:tarjetaempresalist.html";
			
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			//tarjetaempresa/tarjetaempresaform.html?id=245&from=list
			return "/tarjetaempresa/tarjetaempresaform";
		}
	}	
}
